package com.ibm.ba.demo.helper;

import java.io.IOException;
import java.io.StringWriter;

import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.ObjectMapper;

/**
 * 
 * BeanHelper is one utility to display Object by String.
 * 
 * @author Luyi
 *
 */
public class BeanHelper {

	private static Logger logger = Logger.getLogger(BeanHelper.class);

	private static ObjectMapper mapper;

	/**
	 * Convert Object to String.
	 * @param obj
	 * @return String
	 */
	public static String beanToJson(Object obj) {
		try {
			ObjectMapper mapper = getMapperInstance(false);
			StringWriter writer = new StringWriter();
			JsonGenerator gen = new JsonFactory().createJsonGenerator(writer);
			mapper.writeValue(gen, obj);
			gen.close();
			String json = writer.toString();
			writer.close();
			return json;
		} catch (IOException ex) {
			logger.error("beanToJson failed", ex);
			return null;
		}
	}

	public static synchronized ObjectMapper getMapperInstance(boolean createNew) {
		if (createNew) {
			return new ObjectMapper();
		} else if (mapper == null) {
			mapper = new ObjectMapper();
		}
		return mapper;
	}
}
